package com.xjoyt.pay.api.ali;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

public final class OssUtils {

	public static OSSClient getClient(String endpoint, String accessKey, String secretKey) {
		ClientConfiguration conf = new ClientConfiguration();
		conf.setSupportCname(true);
		OSSClient client = new OSSClient(endpoint, accessKey, secretKey, conf);
		return client;
	}

	public static String upload(String endpoint, String accessKey, String secretKey, String bucketName, String fileName,
			String contentType, InputStream input) {
		try (InputStream inputStream = input) {
			OSSClient client = getClient(endpoint, accessKey, secretKey);
			String path = "upload/" + DateFormatUtils.format(new Date(), "yyyy/MM/dd/HH/mm/ss/") + UUID.randomUUID();
			if (StringUtils.isNotBlank(fileName)) {
				path += "-" + fileName;
			}
			ObjectMetadata metadata = new ObjectMetadata();
			if (StringUtils.isNotBlank(contentType))
				metadata.setContentType(contentType);

			client.putObject(bucketName, path, inputStream, metadata);
			return path;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void remove(String endpoint, String accessKey, String secretKey, String bucketName, String path) {
		OSSClient client = getClient(endpoint, accessKey, secretKey);
		client.deleteObject(bucketName, path);
	}

	public static String getUrl(String endpoint, String accessKey, String secretKey, String bucketName, String path) {
		try {
			Date expiration = new Date();
			long epochMillis = expiration.getTime();
			epochMillis += 24 * 3600;
			expiration = new Date(epochMillis);

			OSSClient client = getClient(endpoint, accessKey, secretKey);
			URL url = client.generatePresignedUrl(bucketName, path, expiration);
			return url.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}
}
